package com.code.ui;


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.code.generator.model.ColumnData;
import com.code.generator.model.GeneratorConfiguration;
import com.code.generator.model.GeneratorConfigurationBuilder;
import com.code.generator.model.TableInfo;
import com.code.ui.TableGeneratorPanel;
import com.code.util.StringUtils;
import com.code.util.TransformUtils;
import java.awt.Component;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class DaoCodeGeneratorPanel extends JPanel {
    private static final long serialVersionUID = 1L;
    private JTextField dbUrlTextField;
    private JTextField dbUsernameTextField;
    private JTextField dbPasswordTextField;

    public DaoCodeGeneratorPanel(final GeneratorConfiguration daoConfiguration, final JFrame frame) {
        this.setLayout((LayoutManager)null);
        JLabel lblurl = new JLabel("数据库URL");
        lblurl.setBounds(38, 56, 107, 45);
        this.add(lblurl);
        this.dbUrlTextField = new JTextField();
        this.dbUrlTextField.setBounds(127, 61, 566, 35);
        this.add(this.dbUrlTextField);
        this.dbUrlTextField.setColumns(10);
        
        JLabel label = new JLabel("数据库用户名");
        label.setBounds(38, 92, 107, 45);
        this.add(label);
        this.dbUsernameTextField = new JTextField();
        this.dbUsernameTextField.setColumns(10);
        this.dbUsernameTextField.setBounds(127, 97, 566, 35);
        this.add(this.dbUsernameTextField);
        
        JLabel label_1 = new JLabel("数据库密码");
        label_1.setBounds(38, 130, 107, 45);
        this.add(label_1);
        this.dbPasswordTextField = new JTextField();
        this.dbPasswordTextField.setColumns(10);
        this.dbPasswordTextField.setBounds(127, 135, 566, 35);
        this.add(this.dbPasswordTextField);
        
        JLabel label_2 = new JLabel("第一步：选择数据源");
        label_2.setBounds(38, 20, 274, 15);
        this.add(label_2);
        
        this.dbUrlTextField.setText(daoConfiguration.getDbUrl());
        this.dbUsernameTextField.setText(daoConfiguration.getDbUsername());
        this.dbPasswordTextField.setText(daoConfiguration.getDbPassword());
        
        JButton btnNewButton = new JButton("连接数据库");
        btnNewButton.setBounds(726, 103, 107, 23);
        this.add(btnNewButton);
        
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(127, 180, 566, 259);
        this.add(scrollPane);
        final JList list = new JList();
        scrollPane.setViewportView(list);
        
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(StringUtils.isBlank(DaoCodeGeneratorPanel.this.dbUrlTextField.getText())) {
                    JOptionPane.showMessageDialog((Component)null, "请输入合法的数据库URL");
                } else if(StringUtils.isBlank(DaoCodeGeneratorPanel.this.dbUsernameTextField.getText())) {
                    JOptionPane.showMessageDialog((Component)null, "请输入数据库用户名");
                } else if(StringUtils.isBlank(DaoCodeGeneratorPanel.this.dbUsernameTextField.getText())) {
                    JOptionPane.showMessageDialog((Component)null, "请输入数据库密码");
                } else {
                    DaoCodeGeneratorPanel.this.initDruidDataSource(daoConfiguration, true);
                    DaoCodeGeneratorPanel.this.initDbTable(daoConfiguration, list, true);
                }
            }
        });
        
        JButton buttonExit = new JButton("退出");
        buttonExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        buttonExit.setBounds(519, 459, 93, 23);
        this.add(buttonExit);
        
        final JButton nextButton = new JButton("下一步");
        nextButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                daoConfiguration.setDbUrl(DaoCodeGeneratorPanel.this.dbUrlTextField.getText());
                daoConfiguration.setDbUsername(DaoCodeGeneratorPanel.this.dbUsernameTextField.getText());
                daoConfiguration.setDbPassword(DaoCodeGeneratorPanel.this.dbPasswordTextField.getText());
                daoConfiguration.setSelectTables(StringUtils.join(list.getSelectedValues(), daoConfiguration.getSplitChar()));
                if(StringUtils.isBlank(daoConfiguration.getSelectTables())) {
                    JOptionPane.showMessageDialog((Component)null, "请选择一个表");
                } else {
                    DaoCodeGeneratorPanel.this.initColumnDataForTables(daoConfiguration);
                    GeneratorConfigurationBuilder.buildTableInfo(daoConfiguration.getSelectTableInfoList());
                    nextButton.setEnabled(false);

                    try {
                        frame.getContentPane().removeAll();
                        TableGeneratorPanel e1 = new TableGeneratorPanel(daoConfiguration, frame);
                        frame.getContentPane().add(e1);
                        frame.getContentPane().invalidate();
                        frame.getContentPane().repaint();
                        frame.getContentPane().validate();
                    } catch (Exception var3) {
                        JOptionPane.showMessageDialog((Component)null, "生成失败了：" + var3.getMessage());
                    }

                    nextButton.setEnabled(true);
                }
            }
        });
        nextButton.setBounds(297, 459, 93, 23);
        this.add(nextButton);
        
    }

    private void initColumnDataForTables(GeneratorConfiguration daoConfiguration) {
        daoConfiguration.getSelectTableInfoList().clear();
        String[] tableNames = StringUtils.split(daoConfiguration.getSelectTables(), daoConfiguration.getSplitChar());
        if(tableNames != null && tableNames.length > 0) {
            String[] tableNameArr = tableNames;
            int tableSize = tableNames.length;

            for(int i = 0; i < tableSize; ++i) {
                String tableName = tableNameArr[i];
                TableInfo tableInfo = new TableInfo();
                tableInfo.setTableName(tableName);
                DruidPooledConnection conn = null;

                try {
                    conn = daoConfiguration.getDruidDataSource().getConnection();
                    ResultSet ex = conn.createStatement().executeQuery(daoConfiguration.getTablesInfoSql().replace("@TABLE_SCHEMA", daoConfiguration.getDatabaseName()));

                    while(ex.next()) {
                        if(ex.getString(1).equalsIgnoreCase(tableName)) {
                            tableInfo.setTableComment(ex.getString(2));
                            break;
                        }
                    }

                    ColumnData columnData;
                    for(ResultSet columnResult = conn.createStatement().executeQuery(daoConfiguration.getColumnDatasSql().replace("@TABLE_SCHEMA", daoConfiguration.getDatabaseName()).replace("@TABLE_NAME", tableName)); columnResult.next(); tableInfo.getColumnDataList().add(columnData)) {
                        String dbType = StringUtils.trimToEmpty(columnResult.getString(2));
                        String precision = StringUtils.defaultIfEmpty(columnResult.getString(4), "0");
                        String scale = StringUtils.defaultIfEmpty(columnResult.getString(5), "0");
                        columnData = new ColumnData();
                        columnData.setColumnName(columnResult.getString(1).toUpperCase());
                        columnData.setDataType(TransformUtils.getType(dbType, precision, scale));
                        columnData.setColumnType(columnResult.getString(2));
                        columnData.setColumnComment(StringUtils.trimToEmpty(columnResult.getString(3)));
                        columnData.setPrecision(precision);
                        columnData.setScale(scale);
                        columnData.setCharmaxLength(StringUtils.trimToEmpty(columnResult.getString(6)));
                        columnData.setNullAble(StringUtils.getNullAble(columnResult.getString(7)).equals("Y"));
                        columnData.setDomainPropertyName(TransformUtils.getcolumnNameToDomainPropertyName(columnData.getColumnName()));
                        columnData.setKeyColumn(StringUtils.trimToEmpty(columnResult.getString(8)).toUpperCase().equals("PRI"));
                        columnData.setJdbcDataType(TransformUtils.getJdbcDataType(dbType, precision, scale));
                        columnData.setAutoIncrement(StringUtils.trimToEmpty(columnResult.getString(9)).contains("auto_increment"));
                        if(daoConfiguration.getNeedSumColumns().contains(columnData.getColumnName())) {
                            columnData.setNeedSum(true);
                        }

                        if(!daoConfiguration.getExcludeColumns().contains(columnData.getColumnName())) {
                            tableInfo.getBeanFieldDataTypeSet().add(columnData.getDataType());
                        } else {
                            columnData.setCanUpdate(false);
                            columnData.setQueryColumn(false);
                            columnData.setListColumn(false);
                            columnData.setCanUpdate(false);
                            columnData.setShowDetail(false);
                            columnData.setGenerateDomain(false);
                        }

                        if(columnData.isKeyColumn()) {
                            tableInfo.getColumnKeyDataList().add(columnData);
                        }
                    }

                    daoConfiguration.getSelectTableInfoList().add(tableInfo);
                    continue;
                } catch (Exception var23) {
                    var23.printStackTrace();
                    JOptionPane.showMessageDialog((Component)null, "出错了：" + var23.getMessage());
                } finally {
                    try {
                        conn.close();
                    } catch (Exception var22) {
                        ;
                    }

                }

                return;
            }
        }

    }

    private void initDruidDataSource(GeneratorConfiguration daoConfiguration, boolean showError) {
        if(StringUtils.isBlank(this.dbUrlTextField.getText())) {
            if(showError) {
                JOptionPane.showMessageDialog((Component)null, "请输入数据库JDBC URL");
            }

        } else {
            DruidDataSource druidDataSource = null;

            try {
                druidDataSource = new DruidDataSource();
                druidDataSource.setConnectionErrorRetryAttempts(2);
                druidDataSource.setBreakAfterAcquireFailure(true);
                druidDataSource.setAccessToUnderlyingConnectionAllowed(true);
                druidDataSource.setMaxWait(10000L);
                druidDataSource.setUrl(this.dbUrlTextField.getText());
                druidDataSource.setUsername(this.dbUsernameTextField.getText());
                druidDataSource.setPassword(this.dbPasswordTextField.getText());
                druidDataSource.init();
            } catch (Exception var5) {
                JOptionPane.showMessageDialog((Component)null, "数据库链接出错了：" + var5.getMessage());
            }

            daoConfiguration.setDruidDataSource(druidDataSource);
        }
    }

    private void initDbTable(GeneratorConfiguration conf, JList list, boolean showError) {
        if(StringUtils.isBlank(this.dbUrlTextField.getText())) {
            if(showError) {
                JOptionPane.showMessageDialog((Component)null, "请输入数据库JDBC URL");
            }

        } else {
            DruidPooledConnection conn = null;

            try {
                conn = conf.getDruidDataSource().getConnection();
                conf.setDatabaseName(conn.getCatalog());
                ResultSet ex = conn.getMetaData().getTables((String)null, "%", "%", new String[]{"TABLE"});
                DefaultListModel resultList = new DefaultListModel();

                while(ex.next()) {
                    String tableName = ex.getString("TABLE_NAME");
                    if(!conf.getExcludeTables().contains(tableName)) {
                        resultList.addElement(tableName);
                    }
                }

                list.setModel(resultList);
                return;
            } catch (Exception var17) {
                if(!showError) {
                    return;
                }

                var17.printStackTrace();
                JOptionPane.showMessageDialog((Component)null, "出错了：" + var17.getMessage());
            } finally {
                try {
                    conn.close();
                } catch (Exception var16) {
                    ;
                }

            }

        }
    }
}
